package cn.itcast.wushangxiantu.Fragment.guozhan;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.InputFilter;
import android.text.InputType;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import com.google.gson.Gson;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;

import cn.itcast.wushangxiantu.UserData.User;
import cn.itcast.wushangxiantu.UserData.YuanZhengNumber;
import cn.itcast.wushangxiantu.Activity.Login;
import cn.itcast.wushangxiantu.MessageEvent;
import cn.itcast.wushangxiantu.OkhttpUtil;
import cn.itcast.wushangxiantu.R;
import cn.itcast.wushangxiantu.ToastUtil;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link BianJingLiLianFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class BianJingLiLianFragment extends Fragment {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    private Context context;
    private int gj_id;
    private View view;
    private ViewHolder viewHolder;

    public BianJingLiLianFragment() {
        // Required empty public constructor
    }

    public BianJingLiLianFragment(Context context, int gj_id) {
        this.context = context;
        this.gj_id = gj_id;
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment BianJingLiLian.
     */
    // TODO: Rename and change types and number of parameters
    public static BianJingLiLianFragment newInstance(String param1, String param2) {
        BianJingLiLianFragment fragment = new BianJingLiLianFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment

        view = inflater.inflate(R.layout.fragment_bian_jing_li_lian, container, false);
        viewHolder = new ViewHolder(view);
        return view;
    }

    class ViewHolder implements View.OnClickListener {
        public View rootView;
        public Spinner spNanDu;
        public Button btnYuanZheng;
        public Button btnChongQi;
        public Button btnChongXi;
        public Button btnKaiZhan;
        public TextView tvYuanZhengNumber;
        public TextView tvBossNumber;
        public TextView tvBossXinXi;
        public TextView tvJiaCheng;

        public ViewHolder(View rootView) {
            this.rootView = rootView;
            this.spNanDu = (Spinner) rootView.findViewById(R.id.spNanDu);
            this.btnYuanZheng = (Button) rootView.findViewById(R.id.btnYuanZheng);
            this.btnChongQi = (Button) rootView.findViewById(R.id.btnChongQi);
            this.btnChongXi = (Button) rootView.findViewById(R.id.btnChongXi);
            this.btnKaiZhan = (Button) rootView.findViewById(R.id.btnKaiZhan);
            this.tvYuanZhengNumber = (TextView) rootView.findViewById(R.id.tvYuanZhengNumber);
            this.tvBossNumber = (TextView) rootView.findViewById(R.id.tvBossNumber);
            this.tvBossXinXi = (TextView) rootView.findViewById(R.id.tvBossXinXi);
            this.tvJiaCheng = (TextView) rootView.findViewById(R.id.tvJiaCheng);
            btnChongQi.setOnClickListener(this);
            btnChongXi.setOnClickListener(this);
            btnKaiZhan.setOnClickListener(this);
            btnYuanZheng.setOnClickListener(this);

            getNumber(Login.getUser().getUsernumber(), Login.getUser().getPassword());
        }
        private void GeneralDialogZahuo(final Context context, String title) {
            /**
             * 编辑框
             * 1标题
             */
            AlertDialog dialog;
            final EditText editText = new EditText(context);
            editText.setInputType(InputType.TYPE_CLASS_NUMBER);
            InputFilter[] filters = {new InputFilter.LengthFilter(9)};
            editText.setFilters(filters);
            AlertDialog.Builder builder = new AlertDialog.Builder(context)
                    .setTitle(title)
                    .setView(editText)
                    .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            if (editText.getText().toString().trim().equals("")){
                                dialogInterface.dismiss();
                                ToastUtil.toast(context,"输入有误");
                                return;
                            }
                            int dj= Integer.parseInt(editText.getText().toString());
                            if (dj<1) {
                                ToastUtil.toast(context,"输入有误");
                            } else {
                                setBoss(Login.getUser().getUsernumber(),Login.getUser().getPassword(),dj);
                            }
                        }
                    });
            dialog = builder.create();
            dialog.show();
        }

        private void setBoss(String usernumber, String password, int dj) {
            OkhttpUtil.getRequest(OkhttpUtil.URL_LOG + "&need=setBoss" + "&passWord=" + password + "&userNumber=" + usernumber+"&dj="+dj, new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    try {
                        Log.v("setBoss", e.getMessage());
                    } catch (Exception e1) {

                    }
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String res = response.body().string();
                    Log.v("setBoss", res);
                    Message message = new Message();
                    User user = new Gson().fromJson(res, User.class);
                    message.what = 2;
                    message.obj = user;
                    handler.sendMessage(message);
                }
            });
        }

        public void GeneralDialog(String head, String content, final int num) {
            /**
             * 普通对话框
             * 1标题
             * 2内容
             */
            AlertDialog dialog;
            AlertDialog.Builder builder = new AlertDialog.Builder(context)
                    .setTitle(head)

                    .setMessage(content)
                    .setNegativeButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                          switch (num){
                              case 0:
                                  GoYuanZheng(Login.getUser().getUsernumber(),Login.getUser().getPassword(),spNanDu.getSelectedItemId());
                                  break;
                              case 1:
                                  setBossShuXing(Login.getUser().getUsernumber(),Login.getUser().getPassword());
                                  break;
                              case 2:
                                  daBoss(Login.getUser().getUsernumber(),Login.getUser().getPassword());
                                  break;
                          }
                        }
                    });
            dialog = builder.create();
            dialog.show();
        }

        private void daBoss(String usernumber, String password) {
            OkhttpUtil.getRequest(OkhttpUtil.URL_LOG + "&need=GuoZhandaBoss" + "&passWord=" + password + "&userNumber=" + usernumber, new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    try {
                        Log.v("GuoZhandaBoss", e.getMessage());
                    } catch (Exception e1) {

                    }
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String res = response.body().string();
                    Log.v("GuoZhandaBoss", res);
                    Message message = new Message();
                    User user = new Gson().fromJson(res, User.class);
                    message.what = 2;
                    message.obj = user;
                    handler.sendMessage(message);
                }
            });
        }

        private void setBossShuXing(String usernumber, String password) {
            OkhttpUtil.getRequest(OkhttpUtil.URL_LOG + "&need=setBossShuXing" + "&passWord=" + password + "&userNumber=" + usernumber, new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    try {
                        Log.v("setBossShuXing", e.getMessage());
                    } catch (Exception e1) {

                    }
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String res = response.body().string();
                    Log.v("setBossShuXing", res);
                    Message message = new Message();
                    User user = new Gson().fromJson(res, User.class);
                    message.what = 2;
                    message.obj = user;
                    handler.sendMessage(message);
                }
            });
        }

        private void GoYuanZheng(String usernumber, String password, long selectedItemId) {
            OkhttpUtil.getRequest(OkhttpUtil.URL_LOG + "&need=yuanzheng" + "&passWord=" + password + "&userNumber=" + usernumber+"&nandu="+selectedItemId, new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    try {
                        Log.v("yuanzheng", e.getMessage());
                    } catch (Exception e1) {

                    }
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String res = response.body().string();
                    Log.v("yuanzheng", res);
                    Message message = new Message();
                    User user = new Gson().fromJson(res, User.class);
                    message.what = 2;
                    message.obj = user;
                    handler.sendMessage(message);
                }
            });
        }

        private void getNumber(String usernumber, String password) {
            OkhttpUtil.getRequest(OkhttpUtil.URL_LOG + "&need=getBianJing" + "&passWord=" + password + "&userNumber=" + usernumber, new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    try {
                        Log.v("getBianJing", e.getMessage());
                    } catch (Exception e1) {

                    }
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String res = response.body().string();
                    Log.v("getBianJing", res);
                    Message message = new Message();
                    YuanZhengNumber yuanZhengNumber = new Gson().fromJson(res, YuanZhengNumber.class);
                    message.what = 1;
                    message.obj = yuanZhengNumber;
                    handler.sendMessage(message);
                }
            });
        }

        Handler handler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(@NonNull Message message) {
                switch (message.what) {
                    case 1:
                        YuanZhengNumber yuanZhengNumber = (YuanZhengNumber) message.obj;
                        if (null != yuanZhengNumber) {
                            if (yuanZhengNumber.getSm()<=0){
                                tvBossXinXi.setText("暂无boss信息");
                            }else {
                                tvBossXinXi.setText("等级："+yuanZhengNumber.getBossdj()+"\n血量："+yuanZhengNumber.getBosssm()+"\n防御："+yuanZhengNumber.getBossfy()
                                        +"\n恢复："+yuanZhengNumber.getBosshf()+"\n加成后\n血量："+(yuanZhengNumber.getBosssm()*yuanZhengNumber.getSm())+"\n防御："+(yuanZhengNumber.getBossfy()*yuanZhengNumber.getFy())
                                        +"\n恢复："+(yuanZhengNumber.getBosshf()*yuanZhengNumber.getHf()));
                            }
                            tvJiaCheng.setText(yuanZhengNumber.getSm()+"倍血量"+yuanZhengNumber.getFy()+"倍防御"+yuanZhengNumber.getHf()+"倍恢复");
                            tvBossNumber.setText("今日剩余次数" + yuanZhengNumber.getBossnumber());
                            tvYuanZhengNumber.setText("今日剩余次数" + yuanZhengNumber.getYznumber());
                        } else {
                            ToastUtil.toast(context);
                        }

                        break;
                    case 2:
                        User user = (User) message.obj;
                        if (null != user) {
                           GeneralDialog("远征详情",user.getStw(),-1);
                           getNumber(Login.getUser().getUsernumber(),Login.getUser().getPassword());
                            EventBus.getDefault().post(new MessageEvent("getGuoJiaXinxi"));
                        } else {
                            ToastUtil.toast(context);
                        }

                        break;
                }
                return false;
            }
        });

        @Override
        public void onClick(View view) {
            switch (view.getId()){
                case R.id.btnYuanZheng:
                    GeneralDialog("远征","确定前去远征嘛当前难度为："+spNanDu.getSelectedItem().toString(),0);
                    break;
                case R.id.btnChongQi:
                    GeneralDialogZahuo(context,"输入开启boss等级：这将会消耗(boss等级*1000的战场收益)");
                    break;
                case R.id.btnChongXi:
                    GeneralDialog("仙盟boss","确定重洗boss嘛将会消耗(1000战场收益)",1);
                    break;
                case R.id.btnKaiZhan:
                    GeneralDialog("仙盟boss","确定进攻boss嘛",2);
                    break;
            }
        }
    }
}